package com.cn.aam.checaiduo.ui.product;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.baoyz.widget.PullRefreshLayout;
import com.cn.aam.checaiduo.Const;
import com.cn.aam.checaiduo.R;
import com.cn.aam.checaiduo.backend.RetrofitHome;
import com.cn.aam.checaiduo.backend.observer.OnRequestListener;
import com.cn.aam.checaiduo.backend.rx.RxSchedulers;
import com.cn.aam.checaiduo.base.BaseActivity;
import com.cn.aam.checaiduo.base.BaseFragment;
import com.cn.aam.checaiduo.base.ToolBarManager;
import com.cn.aam.checaiduo.base.adapter.BaseFragmentPagerAdapter;
import com.cn.aam.checaiduo.base.adapter.BaseVLayoutAdapter;
import com.cn.aam.checaiduo.base.adapter.delegator.RecyclerViewDelegatorV2;
import com.cn.aam.checaiduo.bean.ProductItemB;
import com.cn.aam.checaiduo.bean.brandsquence.BrandDataB;
import com.cn.aam.checaiduo.bean.brandsquence.BrandSequenceDataB;
import com.cn.aam.checaiduo.bean.brandsquence.SequenceDataB;
import com.cn.aam.checaiduo.ui.homepage.adapter.CrowdFundAdapter;
import com.cn.aam.checaiduo.ui.homepage.command.CrowdFundListCommand;
import com.cn.aam.checaiduo.ui.product.fragment.BrandListFragment;
import com.cn.aam.checaiduo.ui.product.fragment.SequenceListFragment;
import com.cn.aam.checaiduo.ui.product.vadapter.BrandLinearAdapter;
import com.cn.aam.checaiduo.ui.product.vadapter.SequenceLinearAdapter;
import com.cn.aam.checaiduo.ui.product.vadapter.StickFirstMenuAdapter;
import com.cn.aam.checaiduo.utils.MyEditTextUtils;
import com.cn.aam.checaiduo.utils.MyViewsUtils;
import com.cn.aam.checaiduo.widget.MultiStateView;
import com.cn.aam.checaiduo.widget.WMSnackBar;
import com.flyco.tablayout.SlidingTabLayout;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import butterknife.OnTextChanged;

/**
 * @author 微木森林
 * @time 2017/6/1 下午6:33
 * @description 产品搜索界面
 * @remark
 */
public class ProductSearchActivity extends BaseActivity {

    @BindView(R.id.tab_layout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.vp_search)
    ViewPager vpSearch;

    //列表视图
    @BindView(R.id.id_recyclerview)
    RecyclerView idRecyclerview;
    @BindView(R.id.id_multistateview)
    MultiStateView idMultistateview;
    @BindView(R.id.id_swipe)
    PullRefreshLayout idSwipe;

    @BindView(R.id.recy_defaul)
    RecyclerView recyDefaul;

    @BindView(R.id.et_keyword)
    EditText etKeyword;
    @BindView(R.id.btn_clear)
    ImageView btnClear;

    //v-layout
    private SequenceLinearAdapter sequenceAdapter;
    private BrandLinearAdapter brandAdapter;

    //viewpager
    private BaseFragmentPagerAdapter fragmentAdapter;
    private SequenceListFragment sequenceFragment;
    private BrandListFragment brandFragment;

    //searchList
    private CrowdFundListCommand mCommand;
    private CrowdFundAdapter mAdapter;
    private RecyclerViewDelegatorV2<ProductItemB> mDelegator;


    public static Intent newInstance(Context context) {
        Intent intent = new Intent(context, ProductSearchActivity.class);
        return intent;
    }


    @Override
    protected int layoutId() {
        return R.layout.activity_product_search;
    }

    @Override
    protected void onGenerate() {
        RetrofitHome.getInstance()
                .getInternalApi()
                .getCardBrandList(null)
                .compose(RxSchedulers.<BrandSequenceDataB>toMain())
                .subscribe(new OnRequestListener<BrandSequenceDataB>(this) {
                    @Override
                    public void onNext(BrandSequenceDataB value) {
                        super.onNext(value);
                        if (value.getCode() == Const.REQUEST_FAILED)
                            return;
//                        sequenceAdapter.setDataToAdapter(value.getSequence_data());
//                        brandAdapter.setDataToAdapter(value.getBrand_data());
                        if (sequenceFragment != null) sequenceFragment.addListData(value.getSequence_data());
                        if (brandFragment != null) brandFragment.addListData(value.getBrand_data());
                    }
                });
    }

    @Override
    protected void initView() {
        MyViewsUtils.hideAllViews(btnClear);
        ToolBarManager.with(this, WMContent);
        recyDefaul.requestFocus();
        initTabLayout();
        initSearchList();
        //initVLayout();
    }


    private void initTabLayout() {
        List<BaseFragment> fragmentList = new ArrayList<>();
        fragmentList.add(sequenceFragment = SequenceListFragment.newInstance());
        fragmentList.add(brandFragment = BrandListFragment.newInstance());
        fragmentAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        vpSearch.setAdapter(fragmentAdapter);

        String[] titles = new String[]{"项目期数", "品牌"};
        tabLayout.setViewPager(vpSearch, titles);

        //item click
        sequenceFragment.setItemClickListener(new SequenceListFragment.ItemClickListener() {
            @Override
            public void onClick(SequenceDataB item) {
                etKeyword.setText("第" + item.getStart_sequence() + "~" + item.getEnd_sequence() + "期");
                MyEditTextUtils.setSeletionEnd(etKeyword);

                mCommand.clearAllData();

                mCommand.setStart_sequence(Integer.parseInt(item.getStart_sequence()) + "");
                mCommand.setEnd_sequence(Integer.parseInt(item.getEnd_sequence()) + "");

                Logger.e("第" + mCommand.getStart_sequence() + "~" + mCommand.getEnd_sequence() + "期");
                mDelegator.beginHeaderRefreshing();
                showSearchRecy();
                MyEditTextUtils.hideKeyBorad(etKeyword);
            }
        });
        //item click
        brandFragment.setItemClickListener(new BrandListFragment.ItemClickListener() {
            @Override
            public void onClick(BrandDataB item) {
                etKeyword.setText(item.getBrand());
                doSearch(item.getBrand());
                MyEditTextUtils.hideKeyBorad(etKeyword);
            }
        });
    }

    /**
     * @description 初始化列表
     */
    private void initSearchList() {
        MyViewsUtils.hideAllViews(idMultistateview);
        mCommand = new CrowdFundListCommand();
        mAdapter = new CrowdFundAdapter(mContext);
        mDelegator = new RecyclerViewDelegatorV2<>(this, idMultistateview, idSwipe, idRecyclerview, mAdapter, mCommand);

        mDelegator.setOnItemClickListener(new RecyclerViewDelegatorV2.OnItemClickListener<ProductItemB>() {
            @Override
            public void OnItemClick(ProductItemB item, int position) {
                startActivity(ProductDetailActivity.newInstance(mContext, item.getId(), item.getSequence()));
            }
        });
        mDelegator.setRefreshLayoutEnable(false);
    }

    private void initVLayout() {
        VirtualLayoutManager manager = new VirtualLayoutManager(this);

        recyDefaul.setLayoutManager(manager);
        DelegateAdapter adapter = new DelegateAdapter(manager);

        //一级菜单【项目期数】
        sequenceAdapter = new SequenceLinearAdapter(this);
        sequenceAdapter.setOnItemClick(new BaseVLayoutAdapter.OnItemClick() {
            @Override
            public void onClick(int position) {
                SequenceDataB item = sequenceAdapter.getItem(position);

                etKeyword.setText("第" + item.getStart_sequence() + "~" + item.getEnd_sequence() + "期");
                MyEditTextUtils.setSeletionEnd(etKeyword);

                mCommand.clearAllData();

                mCommand.setStart_sequence(Integer.parseInt(item.getStart_sequence()) + "");
                mCommand.setEnd_sequence(Integer.parseInt(item.getEnd_sequence()) + "");
                mDelegator.beginHeaderRefreshing();
                showSearchRecy();
            }
        });

        //一级菜单【品牌】
        brandAdapter = new BrandLinearAdapter(this);
        brandAdapter.setOnItemClick(new BaseVLayoutAdapter.OnItemClick() {
            @Override
            public void onClick(int position) {
                BrandDataB item = brandAdapter.getItem(position);
                etKeyword.setText(item.getBrand());
                doSearch(item.getBrand());
            }
        });


        adapter.addAdapter(new StickFirstMenuAdapter(this, "项目期数"));
        adapter.addAdapter(sequenceAdapter);
        adapter.addAdapter(new StickFirstMenuAdapter(this, "品牌"));
        adapter.addAdapter(brandAdapter);

        recyDefaul.setAdapter(adapter);

        /**
         * 设置组件复用回收池
         * */
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyDefaul.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 10);
    }


    @OnTextChanged(R.id.et_keyword)
    void onTextChanged(CharSequence text) {
        if (TextUtils.isEmpty(text)) {
            showDefaultRecy();
            MyViewsUtils.hideAllViews(btnClear);
        } else {
            MyViewsUtils.showAllViews(btnClear);
        }

    }

    @OnEditorAction(R.id.et_keyword)
    boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            MyEditTextUtils.hideKeyBorad(etKeyword);
            String keyword = v.getText().toString();
            doSearch(keyword);
            return true;
        }
        return false;
    }


    /**
     * @param keyword 搜索关键词
     * @description 搜索操作
     */
    private void doSearch(String keyword) {
        if (TextUtils.isEmpty(keyword)) {
            WMSnackBar.show(WMContent, "请输入要查询的品牌或期数");
            return;
        }
        MyEditTextUtils.setSeletionEnd(etKeyword);
        mCommand.clearAllData();
        String sequence = getNumberFromString(keyword);
        if (TextUtils.isEmpty(sequence)) {
            //  品牌
            mCommand.setBrand(keyword);
        } else {
            // 期数
            mCommand.setSequence(sequence);
        }
        mDelegator.beginHeaderRefreshing();
        showSearchRecy();
    }

    /**
     * @description 取消搜索，关闭页面
     */
    @OnClick(R.id.btn_cancel)
    public void onClickToCancelSearch() {
        onBackPressed();
    }

    /**
     * @description 清理编辑框内容
     */
    @OnClick(R.id.btn_clear)
    public void onClickToClearSearch() {
        MyEditTextUtils.clearContent(etKeyword);
        showDefaultRecy();
    }


    /**
     * @description 显示默认列表
     */
    private void showDefaultRecy() {
        MyViewsUtils.hideAllViews(recyDefaul);

        MyViewsUtils.showAllViews(tabLayout,vpSearch);
        MyViewsUtils.hideAllViews(idMultistateview);
    }

    /**
     * @description 显示搜索列表
     */
    private void showSearchRecy() {
        MyViewsUtils.hideAllViews(recyDefaul);

        MyViewsUtils.hideAllViews(tabLayout,vpSearch);
        MyViewsUtils.showAllViews(idMultistateview);
    }

    public String getNumberFromString(String str) {
        String target = "";
        if (TextUtils.isEmpty(str)) return "";
        if (str.contains("第") && str.contains("期")) {
            return target = str.substring(str.indexOf("第"), str.indexOf("期"));
        }
        if (str.contains("第") && !str.contains("期")) {
            return target = str.substring(str.indexOf("第"));
        }
        if (!str.contains("第") && str.contains("期")) {
            return target = str.substring(0, str.indexOf("期"));
        }
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                target += str.charAt(i);
            }
        }
        return target;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.slide_out_from_top);
    }


}
